package com.gaojiawei.review;

public class Review1Add {
    public static void main(String[] args) {


    }

    public static ListNode addTwo(ListNode l1,ListNode l2){
        if(l1 == null || l2 == null){
            return l1 == null? l2:l1;
        }
        ListNode head = gelen(l1) >gelen(l2)? l1:l2;
        ListNode curl = l1;
        ListNode curs = l2;
        ListNode last = curl;
        int array = 0;
        while(curl != null && curs != null){
            int sum = curl.val+curs.val+array;
            curl.val = sum%10;
            array = sum/10;
            last = curl;
            curl = curl.next;
            curs = curs.next;
        }
        while (curl != null){
            int sum = curl.val+array;
            curl.val = sum%10;
            array = sum/10;
            last = curl;
            curl = curl.next;
        }
        if(array != 0){
            last.next = new ListNode(array);
        }

        return head;

    }


    public static int gelen(ListNode head){
        int len = 0;
        while(head != null){
            len++;
            head = head.next;
        }
        return len;
    }



    public static ListNode merge(ListNode l1,ListNode l2){
        if(l1 == null || l2 == null){
            return l1 == null ? l2:l1;
        }
        ListNode head = l1.val>l2.val? l2:l1;
        ListNode cur = head;

        ListNode cur1 = head == l1? l1.next:l1;
        ListNode cur2 = head == l1? l2:l2.next;

        while(cur1 != null || cur2 != null){
            if(cur1.val < cur2.val){
                cur.next = cur1;
                cur1 = cur1.next;
                cur = cur.next;
            }else {
                cur.next = cur2;
                cur2 = cur2.next;
                cur = cur.next;
            }
        }
        return head;
    }

    public static class ListNode{
        ListNode next;
        int val;
        public ListNode(int val){
            this.val = val;
        }
    }
}
